package com.banmoon.algorithm.leetcode;

public class Question2 {

    public static void main(String[] args) {
        ListNode A = new ListNode(5);
//        A.next = new ListNode(4);
//        A.next.next = new ListNode(3);

        ListNode B = new ListNode(5);
//        B.next = new ListNode(9);
//        B.next.next = new ListNode(4);
        ListNode result = addTwoNumbers(A, B);

    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int temp = 0;
        ListNode resultNode = new ListNode();
        ListNode currentNode = resultNode;
        do {
            int a = l1.val + l2.val + temp;
            temp = a>=10? 1: 0;
            currentNode.next = new ListNode();
            currentNode = currentNode.next;
            currentNode.val = a%10;

            l1 = l1.next;
            l2 = l2.next;
        }while (l1!=null && l2!=null);
        if(l1!=null)
            temp = addSurplusNode(currentNode, temp, l1);
        if(l2!=null)
            temp = addSurplusNode(currentNode, temp, l2);
        if(temp>0)
            currentNode.next = new ListNode(temp);
        return resultNode.next;
    }

    private static int addSurplusNode(ListNode node, int temp, ListNode surplusNode){
        if(temp==0){
            node.next = surplusNode;
        }else {
            do {
                int sum = surplusNode.val + temp;
                node.next = new ListNode(sum%10);
                temp = sum>=10? 1: 0;

                node = node.next;
                surplusNode = surplusNode.next;
            }while (surplusNode!=null);
        }
        if(temp>0)
            node.next = new ListNode(temp);
        return 0;
    }

}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
